package com.ruoyi.gateway.service.impl;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.gateway.service.ISmsCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 短信验证码实现
 *
 * @author : 小胖
 * @version : 0.0.1
 * @date : 2022/05/12  11:47
 **/
@Service
public class SmsCodeServiceImpl implements ISmsCodeService
{
    @Autowired
    private RedisService redisService;

    /**
     * 下发短信验证码
     *
     * @param phoneNumber 手机号
     * @return 结果
     */
    @Override
    public AjaxResult sendSmsCode(String phoneNumber)
    {
        if ( ! PhoneUtil.isMobile(phoneNumber))
        {
            return AjaxResult.error("手机号码不正确");
        }
        String smsCode = RandomUtil.randomNumbers(6);
        String verifyKey = Constants.SMS_CAPTCHA_CODE_KEY + phoneNumber;
        // 保存到redis
        redisService.setCacheObject(verifyKey, smsCode, Constants.SMS_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // TODO: 下发短信验证码
        System.err.println("号码:" + phoneNumber + " 验证码: " + smsCode);
        return AjaxResult.success(smsCode);
    }

    /**
     * 校验短信验证码
     *
     * @param phoneNumber 手机号
     * @param smsCode 验证码
     */
    @Override
    public void checkSmsCode(String phoneNumber, String smsCode)
    {
        String verifyKey = Constants.SMS_CAPTCHA_CODE_KEY + phoneNumber;
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);

        if ( ! smsCode.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException("短信验证码错误");
        }
    }
}
